package com.itheima.blog.util;

import com.itheima.blog.util.constants.QiNiuYunConstants;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
@Component
public class QiNiuYunUtils {
    private static UploadManager uploadManager;
    private static Auth auth;

    /**
     * 七牛云OSS对象存储简单上传实现
     *   注：文件名重复会覆盖上一个文件
     */
    public static   String store(InputStream inputStream, String contentType, String fileName) {
        if (uploadManager == null) {
            if (auth == null) {
                auth = Auth.create(QiNiuYunConstants.AccessKey, QiNiuYunConstants.SecretKey);
            }
            uploadManager = new UploadManager(new Configuration());
        }

        try {
            String upToken = auth.uploadToken(QiNiuYunConstants.BucketName);
            String keyName = generateKey(fileName);
            Response response = uploadManager.put(inputStream, keyName, upToken, null, contentType);
            return QiNiuYunConstants.Endpoint + "/" + keyName;
        } catch (QiniuException ex) {
            ex.printStackTrace();
        }
        return "";
    }

    private static String generateKey(String fileName) {
        int index = fileName.lastIndexOf('.');
        String suffix = fileName.substring(index);
        String key = getOrderNumber() + suffix;
        return key;
    }

    public static   String getOrderNumber() {
        String orderNumber = DateUtil.dateToString("yyyyMMddHHmmssSS")+(int)(Math.random()*90000 + 10000);
        return orderNumber;
    }


}
